//
//  UIImage+LNG.swift
//  LNGKit
//
//  Created by sun on 2021/4/29.
//

import UIKit

public extension UIImage {
    class func c_getImageWithColor(color: UIColor, viewSize: CGSize) -> UIImage{
        let rect: CGRect = CGRect(x: 0, y: 0, width: viewSize.width, height: viewSize.height)
        UIGraphicsBeginImageContext(rect.size)
        let context: CGContext = UIGraphicsGetCurrentContext()!
        context.setFillColor(color.cgColor)
        context.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsGetCurrentContext()
        return image!
    }
    
    class func c_drawImage(viewSize:CGSize, borderWidth: CGFloat, borderColor: UIColor, radius:CGFloat) -> UIImage {
        //开启上下文
        let imageW: CGFloat = viewSize.width
        let imageH: CGFloat = viewSize.height
        let imageSize = CGSize.init(width: imageW, height: imageH)
        UIGraphicsBeginImageContextWithOptions(imageSize, false, 0.0)
        
        //取得当前的上下文，这里得到的就是上面刚创建的图片上下文
        let context = UIGraphicsGetCurrentContext()
        
        //画边框（大圆）
        let rect = CGRect(x: 0, y: 0, width: imageW, height: imageH)
        
        context?.setStrokeColor(borderColor.cgColor)
        context?.setLineWidth(borderWidth)
        context?.addArc(center: CGPoint(x: imageW/2, y: imageH/2), radius: radius, startAngle: 0, endAngle: .pi*2
        , clockwise: true)
        context?.strokePath()
        context?.addEllipse(in: rect)
        context?.setFillColor(UIColor.red.cgColor)
        context?.fill(rect)
    
        //取图
        let circleFavicon = UIGraphicsGetImageFromCurrentImageContext()
        
        //结束上下文
        UIGraphicsEndImageContext()
        
        return circleFavicon!
    }
    
    func c_scaled(toHeight: CGFloat, isSquare:Bool) -> UIImage? {
        let scale = toHeight / size.height
        let newWidth = isSquare ? toHeight : size.width * scale
        UIGraphicsBeginImageContextWithOptions(CGSize(width: newWidth, height: toHeight), false, 2)
        draw(in: CGRect(x: 0, y: 0, width: newWidth, height: toHeight))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }
    
    class func imageWithColor(color: UIColor, viewSize: CGSize) -> UIImage {
        let rect: CGRect = CGRect(x: 0, y: 0, width: viewSize.width, height: viewSize.height)
        UIGraphicsBeginImageContext(rect.size)
        let context: CGContext = UIGraphicsGetCurrentContext()!
        context.setFillColor(color.cgColor)
        context.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsGetCurrentContext()
        return image!
    }
    
    func c_drawRadiusImage(size:CGSize, radius:CGFloat, fillColor: UIColor) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(size, true, 0)
        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        //设置填充颜色
        fillColor.setFill()
        UIRectFill(rect)
        //利用贝塞尔路径裁切
        let path = UIBezierPath.init(roundedRect: rect, cornerRadius: 24)
        path.addClip()
        UIImage.init().draw(in: rect)
        //获取结果
        let resultImage = UIGraphicsGetImageFromCurrentImageContext()
        //关闭上下文
        UIGraphicsEndImageContext()
        return resultImage!
    }
    
    func compressImageOnlength(maxLength: Int) -> Data? {
        let maxL = maxLength * 1024
        var compress:CGFloat = 0.9
        let maxCompress:CGFloat = 0.1
        var imageData = jpegData(compressionQuality: compress)
        while (imageData?.count)! > maxL && compress > maxCompress {
            compress -= 0.1
            imageData = jpegData(compressionQuality: compress)
        }
        return imageData
    }
    
    ///对指定图片进行拉伸
    func resizableImage(name: String) -> UIImage {
        var normal = UIImage(named: name)!
        let imageWidth = normal.size.width * 0.5
        let imageHeight = normal.size.height * 0.5
        normal = resizableImage(withCapInsets: UIEdgeInsets(top: imageHeight, left: imageWidth, bottom: imageHeight, right: imageWidth))
        return normal
    }
    
    /// 直接使用data进行压缩
    /// - Parameter toKb: 指定data最大的体积
    /// - Returns: data
    func compressOriginalImage(_ toKb: Int = 10485760) -> Data?{
        var compression: CGFloat = 1
        let minCompression: CGFloat = 0.1
        var imageData = self.jpegData(compressionQuality: compression)
        if imageData!.count < toKb {
            return imageData
        }
        while imageData!.count > toKb, compression > minCompression {
            compression -= 0.1
            imageData = self.jpegData(compressionQuality: compression)
        }
        if imageData!.count > toKb {
            return nil
        }
        return imageData
    }

    
    /// 压缩上传图片到指定字节
    /// - Parameters:
    ///   - image: 压缩的图片
    ///   - maxLength: 压缩后最大字节大小
    /// - Returns: 压缩后图片的二进制
    func compressImage(image: UIImage, maxLength: Int) -> Data? {
        let newSize = self.scaleImage(image: image, imageLength: 300)
        let newImage = self.resizeImage(image: image, newSize: newSize)
        
        var compress:CGFloat = 0.9
        var data = newImage.jpegData(compressionQuality: compress)
        
        while data?.count ?? 0 > maxLength && compress > 0.01 {
            compress -= 0.02
            data = newImage.jpegData(compressionQuality: compress)
        }
        return data
    }

    /// 通过指定图片最长边，获得等比例的图片size
    /// - Parameters:
    ///   - image: 原始图片
    ///   - imageLength: 图片允许的最长宽度（高度）
    /// - Returns: 获得等比例的size
    func scaleImage(image: UIImage, imageLength: CGFloat) -> CGSize {
        var newWidth:CGFloat = 0.0
        var newHeight:CGFloat = 0.0
        let width = image.size.width
        let height = image.size.height
    
        if (width > imageLength || height > imageLength) {
            if (width > height) {
                newWidth = imageLength;
                newHeight = newWidth * height / width;
            } else if (height > width) {
                newHeight = imageLength;
                newWidth = newHeight * width / height;
            } else {
                newWidth = imageLength;
                newHeight = imageLength;
            }
        }
        return CGSize(width: newWidth, height: newHeight)
    }
    
    /// 获得指定size的图片
    /// - Parameters:
    ///   - image: 原始图片
    ///   - newSize: 指定的size
    /// - Returns: 调整后的图片
    func resizeImage(image: UIImage, newSize: CGSize) -> UIImage {
        UIGraphicsBeginImageContext(newSize)
        image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
        guard let newImage = UIGraphicsGetImageFromCurrentImageContext() else {
            return UIImage.init()
        }
        UIGraphicsEndImageContext()
        return newImage
    }
}
